package com.zxy.supplier_system.server.entity

import jakarta.persistence.*
import org.hibernate.annotations.DynamicInsert
import org.hibernate.annotations.DynamicUpdate
import org.springframework.data.annotation.CreatedBy
import org.springframework.data.annotation.CreatedDate
import org.springframework.data.jpa.domain.support.AuditingEntityListener
import java.time.OffsetDateTime

/**
 * 送货单
 */
@Entity
@EntityListeners(AuditingEntityListener::class)
@DynamicUpdate
@DynamicInsert
class MarketDeliveryOrder {

    @Id
    var id: Int = 0

    @Column(nullable = false)
    lateinit var number: String

    @OneToOne(cascade = [CascadeType.MERGE])
    @PrimaryKeyJoinColumn
    lateinit var order: MarketOrder

    @CreatedDate
    lateinit var createdDateTime: OffsetDateTime

    @ManyToOne(optional = false)
    @JoinColumn(nullable = false)
    lateinit var market: Market

    @OrderBy("sequence")
    @OneToMany(orphanRemoval = true, mappedBy = "order", cascade = [CascadeType.ALL])
    var goodsList: MutableList<MarketDeliveryOrderItem> = mutableListOf()

    var validatedDateTime :OffsetDateTime? = null

    var auditedDateTime: OffsetDateTime? = null

    @ManyToOne
    @JoinColumn
    @CreatedBy
    var confirmedBy: Employee? = null

    enum class Status{
        WAIT_VALIDATED,
        VALIDATED,
        AUDITED,
    }

    @get:Transient
    val status: Status
        get() {
            return if (validatedDateTime == null) {
                Status.WAIT_VALIDATED
            } else if (auditedDateTime == null) {
                Status.VALIDATED
            } else {
                Status.AUDITED
            }
        }

}